package cn.explink.dop.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.explink.dop.dao.DeliveryManDao;
import cn.explink.dop.dao.OrderDao;
import cn.explink.dop.entity.vo.DeliveryManVO;
import cn.explink.dop.entity.vo.OrderStatusRecordVO;
import cn.explink.dop.entity.vo.OrderVO;
import cn.explink.dop.enums.OrderStatusEnum;
import cn.explink.dop.service.OrderService;
import cn.explink.dop.tools.GetHttpConnect;
import cn.explink.dop.tools.GetProjectUrl;
import cn.explink.eap.core.common.service.impl.CommonServiceImpl;

@Service("orderService")
public class OrderServiceImpl extends CommonServiceImpl implements OrderService {

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private DeliveryManDao deliveryManDao;
	@Override
	public List<OrderVO> getListData(final OrderVO orderVO) {
		return this.orderDao.finds(orderVO);
	}

	@Override
	public Map<String, Object> getListDataByPage(final OrderVO orderVO, String deliveryManName, final int pageNum, final int pageSize) {
		return this.orderDao.findByPage(orderVO, deliveryManName, pageNum, pageSize);
	}

	@Override
	public Integer getCountByStatus(String deliveryManId, List<Integer> statusList) {
		return this.orderDao.getCountByStatus(deliveryManId, statusList);
	}

	@Override
	public List<OrderVO> getOrderVOListByStatusAndDate(String deliveryManId, List<Integer> statusList, Date startDate, Date endDate) {
		List<OrderVO> orderVOList = this.orderDao.getByStatusAndDate(deliveryManId, statusList, startDate, endDate);
		return orderVOList;
	}

	@Override
	public List<OrderVO> getByIdList(List<String> orderIdList) {
		return this.orderDao.getByIdList(orderIdList);
	}

	@Override
	public List<OrderVO> getOrderVOListByStatusAndDate(String deliveryManId, List<Integer> statusList, Date startDate, Date endDate, int pageIndex, int pageCount) {
		List<OrderVO> orderVOList = this.orderDao.getByStatusAndDate(deliveryManId, statusList, startDate, endDate, pageIndex, pageCount);
		return orderVOList;
	}

	/**
	 *
	 * @Title: getTheDayUpMoney
	 * @Description: 当天需要缴纳多少钱和已缴纳多少钱 ：需要缴纳--->当天实收款总减当天取餐付款总数 ：已缴纳--->状态为已成功的
	 * @author 孟凡岭
	 * @param @param userId
	 * @param @return
	 * @throws
	 */
	@Override
	public Map<String, Object> getTheDayUpMoney(String Id) {
		// TODO Auto-generated method stub
		return this.orderDao.getTheDayUpMoney(Id);
	}

	/**
	 *
	 * @Title: getRealityIncome
	 * @Description: 获取当天实际收入
	 * @author 孟凡岭
	 * @param @param userId
	 * @param @return
	 * @throws
	 */
	@Override
	public BigDecimal getRealityIncome(String Id) {
		// TODO Auto-generated method stub
		return this.orderDao.getRealityIncome(Id);
	}

	/**
	 *
	 * @Title: getMonthIncome
	 * @Description: 获取当月实际收入
	 * @author 孟凡岭
	 * @param @param userId
	 * @param @return
	 * @throws
	 */
	@Override
	public BigDecimal getMonthIncome(String userId) {
		// TODO Auto-generated method stub
		return this.orderDao.getMonthIncome(userId);
	}

	/**
	 *
	 * @Title: getDaySuccessOrderList
	 * @Description: 获取当天需要缴纳订单列表，支付方式为现金，按修改时间排序
	 * @author 孟凡岭
	 * @param @param id
	 * @param @return
	 * @throws
	 */
	@Override
	public List<OrderVO> getDaySuccessOrderList(String manId, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		List<OrderVO> list = this.orderDao.getDaySuccessOrderList(manId, pageNum, pageSize);
		return list;
	}

	/**
	 *
	 * @Title: getWaitSendOrder
	 * @Description: 获取待配送的订单，按照送餐时间排序
	 * @author 孟凡岭
	 * @param @param id
	 * @param @param statusList
	 * @param @param pageNum
	 * @param @param pageNumOffset如果pageNumOffset偏移量大于1，则需要从第一条返回(pageNumOffset
	 *        * pageSize)条数据
	 * @param @param pageSize
	 * @param @return
	 * @throws
	 */
	@Override
	public List<OrderVO> getWaitSendOrder(String id, List<Integer> statusList, int pageNum, int pageNumOffset, int pageSize) {
		// TODO Auto-generated method stub
		return this.orderDao.getWaitSendOrder(id, statusList, pageNum, pageNumOffset, pageSize);
	}

	/**
	 *
	 * @Title: getTheDaySuccessOrderDetail
	 * @Description: 获取当天帐单详情
	 * @author 孟凡岭
	 * @param @param id
	 * @param @return
	 * @throws
	 */
	@Override
	public List<Map<String, Object>> getTheDaySuccessOrderDetail(String id, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		return this.orderDao.getTheDaySuccessOrderDetail(id, pageNum, pageSize);
	}

	@Override
	public Map<String, Object> getOrderList(String id, int pageNum, int pageSize) {
		Map<String, Object> map = this.orderDao.getOrderList(id, pageNum, pageSize);
		return map;
	}

	/**
	 *
	 * @Title: getOrderVOListByStatusAndDate4APP
	 * @Description: APP分页查询订单
	 * @author 孟凡岭
	 * @param @param deliveryManId
	 * @param @param statusList
	 * @param @param pageNum 第几页
	 * @param @param pageNumOffset 如果pageNumOffset偏移量大于1，则需要从第一条返回(pageNumOffset
	 *        * pageSize)条数据
	 * @param @param pageSize 每页多少条
	 * @param @param startDate
	 * @param @param endDate
	 * @param @return
	 * @return List<OrderVO> 返回类型
	 * @throws
	 */
	@Override
	public List<OrderVO> getOrderVOListByStatusAndDate4APP(String deliveryManId, List<Integer> statusList, int pageNum, int pageNumOffset, int pageSize, Date startDate, Date endDate) {
		List<OrderVO> orderVOList = this.orderDao.getOrderVOListByStatusAndDate4APP(deliveryManId, statusList, pageNum, pageNumOffset, pageSize, startDate, endDate);
		return orderVOList;
	}

	/**
	 *
	 * @Title: getSysDate
	 * @Description: 获取当前系统时间
	 * @author 孟凡岭
	 * @param @return
	 * @throws
	 */
	@Override
	public Date getSysDate() {
		// TODO Auto-generated method stub
		return this.orderDao.getSystemDate();
	}

	/**
	 *
	 * @Title: getAlreadyMoneyAndOrderList
	 * @Description: 获取已经缴纳金钱的订单列表
	 * @author 孟凡岭
	 * @param @param manId
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @return
	 * @throws
	 */
	@Override
	public List<Map<String, Object>> getAlreadyMoneyAndOrderList(String manId, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		return this.orderDao.getAlreadyMoneyAndOrderList(manId, pageNum, pageSize);
	}

	/**
	 *
	 * @Title: delive
	 * @Description: 分配派送人员，并返回记录数
	 * @author 孟凡岭
	 * @param @param ids
	 * @param @param manId
	 * @param @return
	 * @throws
	 */
	@Override
	public Map<String, Integer> delive(String[] ids, String manId) {
		/**
		 * 可以进行分配的订单状态
		 */
		String[] status = new String[4];
		status[0] = "'" + OrderStatusEnum.NOT_ASSIGN.getValue() + "'";
		status[1] = "'" + OrderStatusEnum.STORE_FRONT_NO_ACCEPT.getValue() + "'";
		status[2] = "'" + OrderStatusEnum.ASSIGNED.getValue() + "'";
		status[3] = "'" + OrderStatusEnum.DISTRIBUTE_REFUSE.getValue() + "'";
		/**
		 * 再查询一次订单，防止多页面时发生重复操作订单
		 */
		List<String> list = this.orderDao.queryNoDeliveByIds(ids, status);
		DeliveryManVO deliveryManVO = deliveryManDao.queryById(manId);
		String name = deliveryManVO.getId();
		int postmanid = deliveryManVO.getPostmanid();
		String deliveryphone = deliveryManVO.getDelTelephone();
		List<Map<String,String>> infolist = new ArrayList<Map<String,String>>();		
		/**
		 * 执行更新
		 */
		this.orderDao.delive(list, manId, name, OrderStatusEnum.ASSIGNED.getValue(),postmanid,deliveryphone);
		/**
		 * 保存状态记录
		 */
		DeliveryManVO man = this.orderDao.get(DeliveryManVO.class, manId);
		int success = list.size();
		Date sysDate = this.orderDao.getSystemDate();
		List<OrderStatusRecordVO> recordList = new ArrayList<OrderStatusRecordVO>();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		for (int i = 0; i < success; i++) {
			OrderStatusRecordVO record = new OrderStatusRecordVO();
			record.setChangTime(sysDate);
			record.setOrderId(list.get(i));
			record.setRecordDesc("订单已经分配给配送员： " + man.getDelName() + "时间:" + sd.format(sysDate));
			recordList.add(record);					
		}
		this.orderDao.batchSave(recordList);		
		/**
		 * 	保存成功后，给快递员推送通知
		 *  请求接口如:http://api.neolix.cn/open/push/new_order?token=ac5f97115cd4df280e37871c7569d862&sign=NEW_ORDER_O2O&postman_id=41&out_trade_no=1375
		 */		
		this.newOrderPushMessage(recordList, man);
				
		/**
		 * 放入成功记录数和失败记录数，如果订单已经分配了则不进行更新
		 */
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("success", success);
		map.put("faild", ids.length - list.size());
		
		
		return map;
	}
	/**
	 * 
	* @Title: newOrderPushMessage 
	* @Description: 订单分配之后，给配送员发送消息的方法
	* @author 小强
	* @param @param recordList
	* @param @param deliveryManVO    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	public void newOrderPushMessage(List<OrderStatusRecordVO> recordList, DeliveryManVO deliveryManVO){
		for(OrderStatusRecordVO temp : recordList ){
			boolean flag = true;
			String param = "token=ac5f97115cd4df280e37871c7569d862";
			
			if(deliveryManVO != null && deliveryManVO.getPostmanid() != null && !"".equals(deliveryManVO.getPostmanid())){//如果这个人存在，并且postman_id也存在且不为空
				param += "&postman_id=" +deliveryManVO.getPostmanid();
				if(temp.getOrderId() != null && !"".equals(temp.getOrderId())){//如果订单的订单id存在且不为空
					param += "&out_trade_no=" + temp.getOrderId();
				}
				else{
					flag = false;
				}
			}else{
				flag = false;
			}
											
			if(flag){
				String url = GetProjectUrl.getNewOrderUrl();
				String results = GetHttpConnect.sendGet(url, param);
				if(results.contains("ok")){
					flag = true;
				}						
			}
			if(!flag){
				//TODO 如果信息推送不成功，那么......
			}				
		}
	}
	/**
	 *
	 * @Title: storeAcceptGetOrderList
	 * @Description: 店面受理查询订单
	 * @author 孟凡岭
	 * @param @param orderVO
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @return
	 * @throws
	 */
	@Override
	public Map<String, Object> storeAcceptGetOrderList(OrderVO orderVO, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		return this.orderDao.storeAcceptGetOrderList(orderVO, pageNum, pageSize);
	}

	/**
	 * @return
	 *
	 * @Title: cancelOrder
	 * @Description: 取消订单
	 * @author 孟凡岭
	 * @param @param ids
	 * @param @param outCauseDesc
	 * @param @param insideCauseDesc
	 * @throws
	 */
	@Override
	public Map<String, Object> cancelOrder(String[] ids, String outCauseDesc, String insideCauseDesc) {
		// TODO Auto-generated method stub
		/**
		 * 订单状态
		 */
		String[] status = new String[4];
		status[0] = "'" + OrderStatusEnum.NOT_ASSIGN.getValue() + "'";
		status[1] = "'" + OrderStatusEnum.ASSIGNED.getValue() + "'";
		status[2] = "'" + OrderStatusEnum.TO_DISTRIBUTE.getValue() + "'";
		status[3] = "'" + OrderStatusEnum.DISTRIBUTE_REFUSE.getValue() + "'";
		// status[4] = "'" + OrderStatusEnum.REFUSE_RECEIVE.getValue() + "'";
		String[] idss = new String[ids.length];
		for (int i = 0; i < ids.length; i++) {
			idss[i] = "'" + ids[i] + "'";
		}
		/**
		 * 获取可以取消的订单ID
		 */
		List<String> orderIds = this.orderDao.getIdByStatusAndId(idss, status, 10);
		/**
		 * 从前台传过来多少订单号
		 */
		int all = ids.length;
		/**
		 * 可以进行处理的订单号
		 */
		int success = orderIds.size();
		this.orderDao.cancelOrder(orderIds.toArray(new String[orderIds.size()]), OrderStatusEnum.STORE_FRONT_NO_ACCEPT.getValue(), outCauseDesc, insideCauseDesc);
		/**
		 * 保存状态记录
		 */
		Date sysDate = this.orderDao.getSystemDate();
		List<OrderStatusRecordVO> recordList = new ArrayList<OrderStatusRecordVO>();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String sysDateStr = sd.format(sysDate);
		for (int i = 0; i < success; i++) {
			OrderStatusRecordVO record = new OrderStatusRecordVO();
			record.setChangTime(sysDate);
			record.setOrderId(orderIds.get(i));
			record.setRecordDesc("门店取消订单，时间:" + sysDateStr);
			recordList.add(record);
		}
		this.orderDao.batchSave(recordList);
		Map<String, Object> map = new HashMap<String, Object>();
		/**
		 * 放入全部订单号数量，成功数量，失败数量
		 */
		map.put("all", all);
		map.put("success", success);
		map.put("fail", all - success);
		return map;
	}

	/**
	 *
	 * @Title: makeFoodSuccess
	 * @Description: 订单备单完成
	 * @author 孟凡岭
	 * @param @param ids
	 * @throws
	 */
	@Override
	public Map<String, Object> makeFoodSuccess(String[] ids) {
		// TODO Auto-generated method stub
		/**
		 * 订单状态
		 */
		String[] status = new String[3];
		status[0] = "'" + OrderStatusEnum.NOT_ASSIGN.getValue() + "'";
		status[1] = "'" + OrderStatusEnum.ASSIGNED.getValue() + "'";
		status[2] = "'" + OrderStatusEnum.TO_DISTRIBUTE.getValue() + "'";
		String[] idss = new String[ids.length];
		for (int i = 0; i < ids.length; i++) {
			idss[i] = "'" + ids[i] + "'";
		}
		/**
		 * 获取可以备单完成的订单ID
		 */
		List<String> orderIds = this.orderDao.getIdByStatusAndId(idss, status, 1);
		/**
		 * 从前台传过来多少订单号
		 */
		int all = ids.length;
		/**
		 * 可以进行处理的订单号
		 */
		int success = orderIds.size();
		this.orderDao.makeFoodSuccess(orderIds.toArray(new String[orderIds.size()]));
		/**
		 * 保存状态记录
		 */
		Date sysDate = this.orderDao.getSystemDate();
		List<OrderStatusRecordVO> recordList = new ArrayList<OrderStatusRecordVO>();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String sysDateStr = sd.format(sysDate);
		for (int i = 0; i < success; i++) {
			OrderStatusRecordVO record = new OrderStatusRecordVO();
			record.setChangTime(sysDate);
			record.setOrderId(orderIds.get(i));
			record.setRecordDesc("门店备单完成，时间:" + sysDateStr);
			recordList.add(record);
		}
		this.orderDao.batchSave(recordList);
		Map<String, Object> map = new HashMap<String, Object>();
		/**
		 * 放入全部订单号数量，成功数量，失败数量
		 */
		map.put("all", all);
		map.put("success", success);
		map.put("fail", all - success);
		return map;
	}

	/**
	 *
	 * @Title: startMakeFood
	 * @Description: 开始备单
	 * @author 孟凡岭
	 * @param @param ids
	 * @throws
	 */
	@Override
	public Map<String, Object> startMakeFood(String[] ids) {
		// TODO Auto-generated method stub
		/**
		 * 订单状态
		 */
		String[] status = new String[3];
		status[0] = "'" + OrderStatusEnum.NOT_ASSIGN.getValue() + "'";
		status[1] = "'" + OrderStatusEnum.ASSIGNED.getValue() + "'";
		status[2] = "'" + OrderStatusEnum.TO_DISTRIBUTE.getValue() + "'";
		String[] idss = new String[ids.length];
		for (int i = 0; i < ids.length; i++) {
			idss[i] = "'" + ids[i] + "'";
		}
		/**
		 * 获取可以备单的订单ID
		 */
		List<String> orderIds = this.orderDao.getIdByStatusAndId(idss, status, 1);
		/**
		 * 从前台传过来多少订单号
		 */
		int all = ids.length;
		/**
		 * 可以进行处理的订单号
		 */
		int success = orderIds.size();
		this.orderDao.startMakeFood(orderIds.toArray(new String[orderIds.size()]));
		/**
		 * 保存状态记录
		 */
		Date sysDate = this.orderDao.getSystemDate();
		List<OrderStatusRecordVO> recordList = new ArrayList<OrderStatusRecordVO>();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String sysDateStr = sd.format(sysDate);
		for (int i = 0; i < success; i++) {
			OrderStatusRecordVO record = new OrderStatusRecordVO();
			record.setChangTime(sysDate);
			record.setOrderId(orderIds.get(i));
			record.setRecordDesc("门店开始备单，时间:" + sysDateStr);
			recordList.add(record);
		}
		this.orderDao.batchSave(recordList);
		Map<String, Object> map = new HashMap<String, Object>();
		/**
		 * 放入全部订单号数量，成功数量，失败数量
		 */
		map.put("all", all);
		map.put("success", success);
		map.put("fail", all - success);
		return map;
	}

	/**
	 *
	 * @Title: getReturnSettleDetail
	 * @Description: 归班反馈中，获取指定配送员当天成功的订单
	 * @author 孟凡岭
	 * @param @param deliveryManId
	 * @param @return
	 * @param @throws Exception
	 * @throws
	 */
	@Override
	public Map<String, Object> getReturnSettleDetail(int pageNum, int pageSize, String deliveryManId, String returnDate, String returnRecordId, int status) throws Exception {
		// TODO Auto-generated method stub
		return this.orderDao.getReturnSettleDetail(pageNum, pageSize, deliveryManId, returnDate, returnRecordId, status);
	}

	/**
	 *
	 * @Title: storeFrontAccept
	 * @Description: 门店接受订单
	 * @author 孟凡岭
	 * @param @param ids
	 * @throws
	 */
	@Override
	public void storeFrontAccept(String[] ids) {
		// TODO Auto-generated method stub
		this.orderDao.storeFrontAccept(ids);
	}

	/**
	 *
	 * @Title: countDeliveryCharge
	 * @Description: 统计派送费用
	 * @author 孟凡岭
	 * @param @param deliveryManId
	 * @param @param startTime
	 * @param @param endTime
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @return
	 * @throws
	 */
	@Override
	public Map<String, Object> countDeliveryCharge(String deliveryManId, String startTime, String endTime, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		return this.orderDao.countDeliveryCharge(deliveryManId, startTime, endTime, pageNum, pageSize);
	}

	/**
	 *
	 * @Title: getSettleDetail
	 * @Description: 获取派费详情
	 * @author 孟凡岭
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @param deliveryManId
	 * @param @param returnDate
	 * @param @return
	 * @throws
	 */
	@Override
	public Map<String, Object> getSettleDetail(int pageNum, int pageSize, String deliveryManId, String returnDate) {
		// TODO Auto-generated method stub
		return this.orderDao.getSettleDetail(pageNum, pageSize, deliveryManId, returnDate);
	}

	/**
	 *
	 * @Title: getRecordDetail
	 * @Description: 通过派费历史记录查看详情
	 * @author 孟凡岭
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @param deliveryManId
	 * @param @param returnDate
	 * @param @param returnRecordId
	 * @param @return
	 * @throws
	 */
	@Override
	public Map<String, Object> getRecordDetail(int pageNum, int pageSize, String deliveryManId, String returnDate, String returnRecordId) {
		// TODO Auto-generated method stub
		return this.orderDao.getRecordDetail(pageNum, pageSize, deliveryManId, returnDate, returnRecordId);
	}

	/**
	 *
	 * @Title: getByIdAndDeliveryManId
	 * @Description: 通过订单号和配送员ID查询订单
	 * @author 孟凡岭
	 * @param @param orderId
	 * @param @param deliveryManId
	 * @param @return
	 * @throws
	 */
	@Override
	public OrderVO getByIdAndDeliveryManId(String orderId, String deliveryManId) {
		// TODO Auto-generated method stub
		return this.orderDao.getByIdAndDeliveryManId(orderId, deliveryManId);

	}
}
